<?php

/**
 * Return a Mime-Type corresponding to an extension
 * @param $extension
 * @return string Mime-Type
 * @author Pablo
 * @since 1.0
 */
function blg_file_get_mime_ext($extension){
	// See URL: stdicon.com
	$list= array(		
		'avi'	=> 'video/x-msvideo',
		'bmp'	=> 'image/bmp',
		'css'	=> 'text/css',
		'exe'	=> 'application/x-msdownload',
		'gif'	=> 'image/gif',
		'gtar'	=> 'application/x-gtar',
		'gz'	=> 'application/x-gzip',
		'htm'	=> 'text/html',
		'html'	=> 'text/html',
		'ico'	=> 'image/x-icon',
		'java'	=> 'text/x-java-source',
		'jpeg'	=> 'image/jpeg',
		'jpg'	=> 'image/jpeg',	
		'log'	=> 'text/plain',
		'm3u'	=> 'audio/x-mpegurl',
		'mid'	=> 'audio/midi',		
		'midi'	=> 'audio/midi',
		'mp3'	=> 'audio/mpeg',
		'mpg'	=> 'video/mpeg',
		'pdf'	=> 'application/pdf',
		'png'	=> 'image/png',
		'rar'	=> 'application/x-rar',
		'tgz'	=> 'application/x-tar',
		'tif'	=> 'image/tiff',
		'txt'	=> 'text/plain',
		'zip'	=> 'application/zip',
		'xml'	=> 'application/xml',
		//Office
		'doc'	=> 'application/msword',
		'mdb'	=> 'application/x-msaccess',
		'pps'	=> 'application/vnd.ms-powerpoint',
		'ppt'	=> 'application/vnd.ms-powerpoint',	
		'xls'	=> 'application/vnd.ms-excel',
		//Office 2007+
		'xlsx'	=> 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
		'xltx'	=> 'application/vnd.openxmlformats-officedocument.spreadsheetml.template',
		'potx'	=> 'application/vnd.openxmlformats-officedocument.presentationml.template',
		'ppsx'	=> 'application/vnd.openxmlformats-officedocument.presentationml.slideshow',
		'pptx'	=> 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
		'sldx'	=> 'application/vnd.openxmlformats-officedocument.presentationml.slide',
		'docx'	=> 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
		'dotx'	=> 'application/vnd.openxmlformats-officedocument.wordprocessingml.template',
		'xlam'	=> 'application/vnd.ms-excel.addin.macroEnabled.12',
		'xlsb'	=> 'application/vnd.ms-excel.sheet.binary.macroEnabled.12',
	
		/*
		'txt' => 'text/plain',
		'htm' => 'text/html',
		'html' => 'text/html',
		'php' => 'text/html',
		'css' => 'text/css',
		'js' => 'application/javascript',
		'json' => 'application/json',
		'xml' => 'application/xml',
		'swf' => 'application/x-shockwave-flash',
		'flv' => 'video/x-flv',
		
		// images
		'png' => 'image/png',
		'jpe' => 'image/jpeg',
		'jpeg' => 'image/jpeg',
		'jpg' => 'image/jpeg',
		'gif' => 'image/gif',
		'bmp' => 'image/bmp',
		'ico' => 'image/vnd.microsoft.icon',
		'tiff' => 'image/tiff',
		'tif' => 'image/tiff',
		'svg' => 'image/svg+xml',
		'svgz' => 'image/svg+xml',
		
		// archives
		'zip' => 'application/zip',
		'rar' => 'application/x-rar-compressed',
		'exe' => 'application/x-msdownload',
		'msi' => 'application/x-msdownload',
		'cab' => 'application/vnd.ms-cab-compressed',
		
		// audio/video
		'mp3' => 'audio/mpeg',
		'qt' => 'video/quicktime',
		'mov' => 'video/quicktime',
		
		// adobe
		'pdf' => 'application/pdf',
		'psd' => 'image/vnd.adobe.photoshop',
		'ai' => 'application/postscript',
		'eps' => 'application/postscript',
		'ps' => 'application/postscript',
		
		// ms office
		'doc' => 'application/msword',
		'rtf' => 'application/rtf',
		'xls' => 'application/vnd.ms-excel',
		'ppt' => 'application/vnd.ms-powerpoint',
		
		// open office
		'odt' => 'application/vnd.oasis.opendocument.text',
		'ods' => 'application/vnd.oasis.opendocument.spreadsheet',		 
		 */
	);
	
	if(array_key_exists($extension, $list))
		return $list[$extension];
	
	return NULL;
}

/**
 * Returns the mime type of a fisical file
 * @param string $filename
 * @return The mime type
 * @author Pablo;
 * @since 1.0
 */
function blg_file_get_mime($file){
	if(file_exists($file))
		return mime_content_type($file);	
}

/**
 * Replace accents char to their none accent char
 * @param string $var
 * @author Pablo
 * @since 1.0
 */
function blg_file_replace_acc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', 'ŵ', 'Ŷ', 'ŷ', 'Ÿ', 'Ź', 'ź', 'Ż', 'ż', 'Ž', 'ž', 'ſ', 'ƒ', 'Ơ', 'ơ', 'Ư', 'ư', 'Ǎ', 'ǎ', 'Ǐ', 'ǐ', 'Ǒ', 'ǒ', 'Ǔ', 'ǔ', 'Ǖ', 'ǖ', 'Ǘ', 'ǘ', 'Ǚ', 'ǚ', 'Ǜ', 'ǜ', 'Ǻ', 'ǻ', 'Ǽ', 'ǽ', 'Ǿ', 'ǿ'); 
    $b = array('A', 'A', 'A', 'A', 'A', 'A', 'AE', 'C', 'E', 'E', 'E', 'E', 'I', 'I', 'I', 'I', 'D', 'N', 'O', 'O', 'O', 'O', 'O', 'O', 'U', 'U', 'U', 'U', 'Y', 's', 'a', 'a', 'a', 'a', 'a', 'a', 'ae', 'c', 'e', 'e', 'e', 'e', 'i', 'i', 'i', 'i', 'n', 'o', 'o', 'o', 'o', 'o', 'o', 'u', 'u', 'u', 'u', 'y', 'y', 'A', 'a', 'A', 'a', 'A', 'a', 'C', 'c', 'C', 'c', 'C', 'c', 'C', 'c', 'D', 'd', 'D', 'd', 'E', 'e', 'E', 'e', 'E', 'e', 'E', 'e', 'E', 'e', 'G', 'g', 'G', 'g', 'G', 'g', 'G', 'g', 'H', 'h', 'H', 'h', 'I', 'i', 'I', 'i', 'I', 'i', 'I', 'i', 'I', 'i', 'IJ', 'ij', 'J', 'j', 'K', 'k', 'L', 'l', 'L', 'l', 'L', 'l', 'L', 'l', 'l', 'l', 'N', 'n', 'N', 'n', 'N', 'n', 'n', 'O', 'o', 'O', 'o', 'O', 'o', 'OE', 'oe', 'R', 'r', 'R', 'r', 'R', 'r', 'S', 's', 'S', 's', 'S', 's', 'S', 's', 'T', 't', 'T', 't', 'T', 't', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'W', 'w', 'Y', 'y', 'Y', 'Z', 'z', 'Z', 'z', 'Z', 'z', 's', 'f', 'O', 'o', 'U', 'u', 'A', 'a', 'I', 'i', 'O', 'o', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'A', 'a', 'AE', 'ae', 'O', 'o'); 
    $var= str_replace($a, $b,$var);
    return $var; 
}

/**
 * Returns the extension of a filename
 * @param $filename
 * @return [String|NULL] The extension
 * @author Pablo
 * @since 1.0
 */
function blg_get_filename_extension($filename){
	$ext= (strpos($filename, '.')!==FALSE?strtolower(end(explode(".", $filename))):NULL);
	return $ext;	
}

/**
 * Sanitize a filename string
 * @param $filename
 * @author Pablo
 * @since 1.0
 */
function blg_file_sanitize_filename($filename, $is_path= FALSE) {
	$filename= blg_file_replace_accents($filename);
	$filename= strtolower(trim($filename));

	// replace spaces
	$find= array('/[[:space:]]/');
	$repl= array('_');
	$filename= preg_replace($find, $repl, $filename);

	// adding - union characters
	$find= ($is_path!==FALSE?array('&', '+', ','):array('&', '+', ',', '/', '\\'));
	$filename= str_replace ($find, '-', $filename);
 
	// delete and replace rest of special chars
	$find= array('/[\-]+/', '/[_]+/', '/[^a-z0-9\-_\.\\/()]/');
	$repl= array('-', '_', '');
	$filename= preg_replace ($find, $repl, $filename);
 
	return $filename; 
}

/**
 * Increment filename, usefull if a file already exists with the same filename
 * @param $filename
 * @param $i
 */
function blg_file_name_inc($filename, $i=0){
	$name= $filename;
	$parts = explode('.', $name);
	if(count($parts)>1){
		array_pop($parts);
		$name = implode(".", $parts);
	}	
	$ext= blg_get_filename_extension($filename);
	
	if(!empty($ext))
		return $name.'_('.$i.').'.$ext;
	
	return $name.'_('.$i.')';	
}

/**
 * Checks if an extension corresponds to an image type
 * @param $file_mime
 * @param $type
 * @author Pablo
 * @since 1.0
 */
function blg_filename_is_image($filename){
	$image_exts= array('jpg', 'png', 'gif', 'bmp');
	return in_array(blg_get_filename_extension($filename), $image_exts);
}

/**
 * Checks if a mime corresponds to a specified type
 * @param $file_mime
 * @param $type
 * @author Pablo
 * @since 1.0
 */
function blg_file_mime_is($file_mime, $type){
	$prefix= substr(strtolower($file_mime), 0, strlen($type));
	return ($prefix===strtolower($type));			
}

/**
 * Upload a file to a $path
 * @param $input_file_name
 * @param $path
 * @return [$uploaded_path|FALSE]
 * @author Pablo
 * @since 1.0
 */
function blg_upload_file($input_file_name, $path='', $mode= '0755'){
	if (is_uploaded_file($_FILES[$input_file_name]['tmp_name'])) {
		if($_FILES[$input_file_name]['error']==UPLOAD_ERR_OK){
			//GET DATA
	        $name = $_FILES[$input_file_name]['name'];	        
	        $mime = $_FILES[$input_file_name]['type'];
	        $size = intval($_FILES[$input_file_name]['size']);
	        $tmp_path= $_FILES[$input_file_name]["tmp_name"];
	     
	     	//UPLOAD SIZE
	        if($size > blg_get_config('upload_max_filesize')){
	        	blg_msg_add(blg_echo('error:upload:max_file_size'), TRUE);
	        	return FALSE;
	        }
	        	
	        //SANITIZE FILENAME AND PATH
	        $filename= blg_file_sanitize_filename($name);	        	        
			$dir= blg_get_user_files_path().add_trainling_slash($path,DS);
			$destination= $dir.$filename;	        
	         
	        $i=1;
			while(file_exists($destination)){
				$destination= $dir . blg_file_name_inc($filename,$i);
				$i++;	
			}
			
			//MOVE FILE
			if(!is_dir($dir) && !mkdir($dir, $mode, TRUE)){
				blg_msg_add(blg_echo('error:upload:unknow', array($name)), TRUE);
				return FALSE;
			}
			
	        if(!move_uploaded_file($_FILES[$input_file_name]["tmp_name"], $destination)){
				blg_msg_add(blg_echo('error:upload:unknow', array($name)), TRUE);
				return FALSE;	        	
	        }			
			
			//INFO
			if(blg_file_mime_is($mime, 'image')){
				//TODO Generate thumnails		
			}
			
	        //DONE!
	        blg_msg_add(blg_echo('error:upload:'.UPLOAD_ERR_OK, array($name)));	
	        return $destination;
		}
		blg_msg_add(blg_echo('error:upload:'.$_FILES[$input_file_name]['error']), TRUE);
	}			
	return FALSE;	
}

/**
 * Checks if a logcal file (URL) exists
 * @param String $file_url URL
 * @return [FALSE|String] The fisical image path
 * @author Pablo
 * @since 1.0
 */
function blg_file_exists($file_url){
	$url= blg_get_url_parts($file_url);	
	$pages= $url->pages;
	
	if('files'==array_shift($pages)){	
		$user= blg_get_user_entity_by_code(array_shift($pages), false);		
		if(!empty($user)){
			$path= blg_get_user_files_path($user).implode(DS, $pages);
			if(file_exists($path)){
				return $path;		
			}	
		}			
	}
	
	return FALSE;
}

/**
 * Alias for <i>blg_file_exists($file_url)</i>
 * @param String $file_url URL
 * @return [FALSE|String] The fisical image path
 * @author Pablo
 * @since 1.0
 */
function file_url_to_path($file_url){
	return blg_file_exists($file_url);
}


